package so.ifl.servcie.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import so.ifl.commons.tools.Constant;
import so.ifl.commons.tools.DateUtil;
import so.ifl.commons.tools.StringHelper;
import so.ifl.dao.CompanyInfoDao;
import so.ifl.dao.ExamBookingDetailInfoDao;
import so.ifl.dao.ExamBookingInfoDao;
import so.ifl.dao.ExamHistoryDao;
import so.ifl.dao.OfficeInfoDao;
import so.ifl.dao.ResultInfoDao;
import so.ifl.dao.StudentInfoDao;
import so.ifl.dao.SysDao;
import so.ifl.servcie.ExamBookingService;
import so.ifl.vo.AccountVo;
import so.ifl.vo.CompanyVo;
import so.ifl.vo.ExamBookingDetailVo;
import so.ifl.vo.ExamBookingVo;
import so.ifl.vo.ExamHistoryVo;
import so.ifl.vo.OfficeVo;
import so.ifl.vo.ResultVo;
import so.ifl.vo.StudentVo;

/**
 * 
 * create by simon
 * create at 2012-1-17 下午11:21:14
 * <mailto:liangyuanliu@gmail.com>
 */
@Service("exambookingService")
public class ExamBookingServcieImpl implements ExamBookingService {

	@Autowired
	private ExamBookingInfoDao exambookingInfoDao;
	
	@Autowired
	private ExamBookingDetailInfoDao examBookingDetailInfoDao;
	
	@Autowired
	private ResultInfoDao resultInfoDao;
	
	@Autowired
	private StudentInfoDao studentInfoDao;
	
	@Autowired
	private CompanyInfoDao companyInfoDao;
	
	@Autowired
	private ExamHistoryDao examHistoryDao;
	
	@Autowired
	private SysDao sysDao;
	
	@Autowired
	private OfficeInfoDao officeInfoDao;
	
	
	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	/**
	 * 查询考试历史
	 * create by aaron.lu
	 * create at 2012-5-11 下午9:36:48
	 * <mailto: atyuan.lu@gmail.com>
	 * @param params
	 * @param offset
	 * @param limit
	 * @return
	 *
	 */
	public List<ExamHistoryVo> queryExamHistory(Map<String, Object> params, Integer offset, Integer limit){
		return examHistoryDao.queryExamHistory(params, new RowBounds(offset, limit));
	}
	
	/**
	 * 统计考试记录
	 * create by aaron.lu
	 * create at 2012-5-11 下午9:37:41
	 * <mailto: atyuan.lu@gmail.com>
	 * @param params
	 * @return
	 *
	 */
	public int countExamHistory(Map<String, Object> params){
		return examHistoryDao.countExamHistory(params);
	}

	public List<ExamBookingVo> queryExamBookingWithParamAndPagination(Map<String, Object> params, Integer offset, Integer limit) {
		return exambookingInfoDao.queryExamBookingWithParamAndPagination(
				params, new RowBounds(offset, limit));
	}

	public Integer countExamBookingWithParam(Map<String, Object> params) {
		return exambookingInfoDao.countExamBookingWithParam(params);
	}

	public void insertExamBooking(ExamBookingVo examBookingVo) {
		String examCode = sysDao.getSeq(Constant.JXT_EXAM_SEQ);		
		examBookingVo.setExamCode(examCode);//获取流水号
		examBookingVo.setExamStatus("0");//初始状态
		exambookingInfoDao.insertExamBooking(examBookingVo);
	}

	public void updateExamBooking(ExamBookingVo examBookingVo) {
		exambookingInfoDao.updateExamBooking(examBookingVo);

	}

	public void deleteExamBooking(Integer exambookingId) {
		examBookingDetailInfoDao.deleteExamBookingDetailByMain(exambookingId);
		exambookingInfoDao.deleteExamBooking(exambookingId);
		
	}
	
	/**
	 * 保存考试预约信息
	 * create by aaron.lu
	 * create at 2012-3-7 上午12:49:26
	 * <mailto: atyuan.lu@gmail.com>
	 * @param dataSetExamBooking
	 * @param dataSetExamBookingDetail
	 * @throws Exception 
	 *
	 */
	public void saveExamBookingInfo(ArrayList<ExamBookingVo> dataSetExamBooking, ArrayList<ExamBookingDetailVo> dataSetExamBookingDetail) throws Exception{
		if (null != dataSetExamBooking && dataSetExamBooking.size() > 0) {
			ExamBookingVo examBookingVo = dataSetExamBooking.get(0);
			
			Map<String, Object> params = new HashMap<String, Object>();
			try {
				params.put("less_time_", DateUtil.getFirstSecondInDay(examBookingVo.getExamBookingDate()));
				params.put("bigger_time", DateUtil.getLastSecondInDay(examBookingVo.getExamBookingDate()));
				params.put("test_type_", examBookingVo.getTestType());
				params.put("trainer_car_id_", null != examBookingVo.getTrainerCarId()?examBookingVo.getTrainerCarId():100000);
			} catch (Exception e) {
				logger_.error("parse date error:" + e.getMessage());
			}
			
//			int total_exambooking = exambookingInfoDao.countExamBookingWithParam(params);
//			
//			if (total_exambooking > 0) {
//				throw new Exception("该教练已经负责其他的场次考试...");
//			}
//			教练取消同一天可以预约的场次  2013/07/28
			
			
			if (null != dataSetExamBookingDetail && dataSetExamBookingDetail.size() > 0) {
				params.put("student_id_", dataSetExamBookingDetail.get(0).getStudentId());				
				List<OfficeVo> officeVos = officeInfoDao.queryOfficeByStudent(params);				
				if (null != officeVos && officeVos.size() > 0) {
					examBookingVo.setCompanyName(officeVos.get(0).getOfficeNote()); 
				}
				
			}
			
			String examCode = sysDao.getSeq(Constant.JXT_EXAM_SEQ);		
			examBookingVo.setExamCode(examCode);//获取流水号
			examBookingVo.setExamStatus("0");//初始状态
			exambookingInfoDao.insertExamBooking(examBookingVo);
			
			int lastInsertId = sysDao.getLastInsertID();
			
			if (null != dataSetExamBookingDetail && dataSetExamBookingDetail.size() > 0) {
				for (int i = 0; i < dataSetExamBookingDetail.size(); i++) {
					ExamBookingDetailVo examBookingDetailVo = dataSetExamBookingDetail.get(i);
					examBookingDetailVo.setExamBookingId(lastInsertId);
					examBookingDetailInfoDao.insertExamBookingDetail(examBookingDetailVo);
				}
			}
		}
	}
	
	/**
	 * 回表
	 * create by aaron.lu
	 * create at 2012-5-11 上午11:12:18
	 * <mailto: atyuan.lu@gmail.com>
	 * @param examBookingId
	 * @param accountVo
	 * @return
	 *
	 */
	public boolean returnBill(Integer examBookingId, AccountVo accountVo){
		boolean flag = true;
		if (null !=  examBookingId) {
			
			Map<String, Object> queryExamBookingDetailParams = new HashMap<String, Object>();
			queryExamBookingDetailParams.put("exam_booking_id_", examBookingId);
			
			List<ExamBookingVo> examBookingVos = exambookingInfoDao.queryExamBookingWithParamAndPagination(queryExamBookingDetailParams, new RowBounds(0, 10000));
			if(null != examBookingVos && examBookingVos.size() > 0){
				ExamBookingVo examBookingVo = examBookingVos.get(0);
				examBookingVo.setExamStatus("1");//回表
				examBookingVo.setLastModifyUser(accountVo.getAccountLoginName());
				examBookingVo.setLastModifyTime(new Date());
				exambookingInfoDao.updateExamBooking(examBookingVo);
				
				List<ExamBookingDetailVo> examBookingDetailVos = examBookingDetailInfoDao.queryExamBookingDetailWithParamAndPagination(queryExamBookingDetailParams, new RowBounds(0, 10000));
				if (null != examBookingDetailVos && examBookingDetailVos.size() > 0) {
					for (int i = 0; i < examBookingDetailVos.size(); i++) {
						ExamBookingDetailVo examBookingDetailVo = examBookingDetailVos.get(i);
						
						Map<String, Object> queryResultInfoParams = new HashMap<String, Object>();
						queryResultInfoParams.put("student_id_", examBookingDetailVo.getStudentId());
						List<ResultVo> resultVos = resultInfoDao.queryResultOfStudent(queryResultInfoParams);
						List<StudentVo> studentVos = studentInfoDao.queryStudentWithParamAndPagination(queryResultInfoParams, new RowBounds(0, 10000));
						if (null != resultVos && resultVos.size() > 0) {
							ResultVo resultVo = resultVos.get(0);
							StudentVo studentVo = studentVos.get(0);
							if (null != examBookingVo.getExaminationSubjects()) {
								String source = DateUtil.YMD_SDF.format(new Date());
								switch (examBookingVo.getExaminationSubjects()) {
								case 1:
									resultVo.setTest1Result(examBookingDetailVo.getExamResult());
									resultVo.setSource1(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("2");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("3");
										studentVo.setNeedToPay(Constant.INT_TRUE_VALUE.toString());//科目一不合格，需要交纳补考费用后才能预约考试，add at 20130225
									}
									break;
								case 2:
									resultVo.setTest2Result(examBookingDetailVo.getExamResult());
									resultVo.setSource2(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("4");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("5");
										studentVo.setNeedToPay(Constant.INT_TRUE_VALUE.toString());//科目二不合格，需要交纳补考费用后才能预约考试，add at 20130225
									}
									break;
								case 3:
									resultVo.setTest3Result(examBookingDetailVo.getExamResult());
									resultVo.setSource3(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("6");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("7");
									}
									break;
								case 4:
									resultVo.setTest4Result(examBookingDetailVo.getExamResult());
									resultVo.setSource4(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("8");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("8");
									}
									break;
								case 5:
									resultVo.setTest5Result(examBookingDetailVo.getExamResult());
									resultVo.setSource5(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("9");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("9");
									}
									break;
								case 6:
									resultVo.setTest6Result(examBookingDetailVo.getExamResult());
									resultVo.setSource6(source);
									if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("100")) {
										studentVo.setStudentProgress("11");
									}else if (StringHelper.isNotEmpty(examBookingDetailVo.getExamResult()) && examBookingDetailVo.getExamResult().equals("50")) {
										studentVo.setStudentProgress("10");
										studentVo.setNeedToPay(Constant.INT_TRUE_VALUE.toString());//科目三不合格。需要交纳补考费用后才能预约考试，add at 20130225
									}
									break;

								default:
									break;
								}
							}
							ExamHistoryVo examHistoryVo = new ExamHistoryVo(
									examBookingDetailVo.getStudentId(),
									examBookingVo.getExamBookingDate(),
									new Date(),
									examBookingVo.getExaminationSubjects(),
									examBookingDetailVo.getExamResult(),
									examBookingVo.getExamCode(),
									accountVo.getAccountOwner(),
									accountVo.getAccountLoginName(),
									new Date(),
									accountVo.getAccountLoginName(), new Date());
							
							examHistoryDao.insertExamHistory(examHistoryVo);
							resultInfoDao.updateResult(resultVo);
							studentInfoDao.updateStudent(studentVo);
						}
					}		
				}
			}else{
				flag = false;//无预约表提交
			}
			
			
		}
		
		return flag;
	}
}
